from math import fabs
import os
import sys
from PySide6.QtWidgets import QApplication, QMainWindow, QMessageBox
from PySide6.QtCore import QTimer


from ui_hall import Ui_MainWindow
import serial.tools.list_ports


class MainWindow(QMainWindow):
    baud_value = 115200  # 实际波特率
    com_value = 0  # 实际串口号
    serial_switch_status = True  # 串口开关状态开关true/false
    led_status = 0  # LED灯状态 0未知 1点亮 2熄灭

    def __init__(self):
        super().__init__()
        global config_dict
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.timer = QTimer(self)
        self.timer.timeout.connect(self.time_out)
        # self.ui.comView.addItems(port_array)

        self.ui.btnSwitch.clicked.connect(self.btnSwitchHandle)
        self.ui.btnLED.clicked.connect(self.btnLEDHandle)
        self.ui.baudView.currentIndexChanged.connect(self.baudChangeHandle)
        self.ui.comView.currentIndexChanged.connect(self.comChangeHandle)

    def time_out(self):
        global ser
        data = ser.read_all()
        if data != b'':
            data = data.decode('utf-8')
            print('收到内容:{}'.format(data))
            if data == 'LED_ON':
                self.led_status = 1
                self.ui.btnLED.setText('on')
                self.ui.iconLED.setStyleSheet(
                    "#iconLED{image: url(:/image/image/dengpao5hao.png);}")
                pass

            elif data == 'LED_OFF':
                self.led_status = 2
                self.ui.btnLED.setText('off')
                self.ui.iconLED.setStyleSheet(
                    "#iconLED{image: url(:/image/image/dengpao1hao.png);}")
                pass

        self.timer.start(100)

    def btnSwitchHandle(self):
        if self.ui.comView.currentText != '':
            ser.baudrate = self.ui.baudView.currentText()
            ser.port = self.ui.comView.currentText()

            print(self.ui.comView.currentText(),
                  self.ui.baudView.currentText(),
                  self.ui.btnSwitch.text())
            if self.ui.btnSwitch.text() == "打开":
                try:
                    ser.open()
                except:
                    QMessageBox.critical(self, "Port Error", "此串口不能被打开！")
                    return None
                # 打开串口接收定时器，周期为100ms
                ser.write(b'LED_OFF')  # LED灯熄灭
                ccc = '{"COM":"'+self.ui.comView.currentText() + \
                    '","baud":"'+self.ui.baudView.currentText()+'"}'
                file = open('./config.txt', 'w')
                file.write(ccc)
                file.close()
                self.timer.start(100)
                self.ui.btnSwitch.setText("断开")
                self.ui.iconCOM.setStyleSheet(
                    "#iconCOM{image: url(:/image/image/connection.png);}")
                self.ui.btnSwitch.setStyleSheet(
                    "#btnSwitch{background-color: green}")
            else:
                self.timer.stop()
                ser.close()
                self.ui.btnSwitch.setText("打开")
                self.ui.iconCOM.setStyleSheet(
                    "#iconCOM{image: url(:/image/image/disconnect.png);}")
                window.ui.btnSwitch.setStyleSheet(
                    "#btnSwitch{background-color: red}")
        else:
            print("电脑没有串口")

    def btnLEDHandle(self):
        if self.led_status != 1:
            self.led_status = 1
            ser.write(b'LED_ON')  # LED灯点亮

        elif self.led_status == 1:
            self.led_status = 2
            ser.write(b'LED_OFF')  # LED灯熄灭

        pass

    def baudChangeHandle(self):
        ser.baudrate = self.ui.baudView.currentText()

    def comChangeHandle(self):
        print("comChangeHandle", self.ui.btnSwitch.text())

        if self.ui.btnSwitch.text() == '断开':
            self.timer.stop()
            ser.close()
            ser.port = self.ui.comView.currentText()
            try:
                ser.open()
            except:
                QMessageBox.critical(self, "Port Error", "此串口不能被打开！")
                self.ui.btnSwitch.setText("打开")
                self.ui.iconCOM.setStyleSheet(
                    "#iconCOM{image: url(:/image/image/disconnect.png);}")
                window.ui.btnSwitch.setStyleSheet(
                    "#btnSwitch{background-color: red}")
                return None
            ser.write(b'LED_OFF')  # LED灯熄灭
            self.timer.start(100)
        else:
            pass


def file_write():
    pass


if __name__ == "__main__":
    # 创建主界面
    app = QApplication(sys.argv)

    window = MainWindow()
    window.show()

    # 读取之前的串口配置，免得每次都要打开都要选串口和波特率.
    if os.path.exists('./config.txt'):
        file = open('./config.txt', 'r')
        str = file.read()
        if str != '':
            config_dict = eval(str)
        file.close()
    else:
        file = open('./config.txt', 'w+')
        file.write('{"COM":"","baud":""}')
        config_dict = {"COM": "", "baud": ""}
        file.close()

    print("串口配置情况:", config_dict)
    # 列出所有当前的com口
    port_array = []
    port_list = list(serial.tools.list_ports.comports())
    if len(port_list) > 0:
        for i in range(len(port_list)):
            port_array.append(list(port_list[i])[0])

    window.ui.comView.addItems(port_array)

    # 判断先前的串口是否现在还存在,不存在的话串口不打开

    com_exist = window.ui.comView.findText(config_dict["COM"])
    baud_exist = window.ui.baudView.findText(config_dict["baud"])

    ser = serial.Serial(timeout=0.5)
    if baud_exist < 0:
        window.ui.baudView.setCurrentIndex(0)
    else:
        window.ui.baudView.setCurrentIndex(baud_exist)

    if com_exist < 0:
        window.ui.comView.setCurrentIndex(0)
        window.ui.btnSwitch.setText("断开")
        window.ui.iconCOM.setStyleSheet(
            "#iconCOM{image: url(:/image/image/connection.png);}")
        window.ui.btnSwitch.setStyleSheet(
            "#btnSwitch{background-color: green}")

    else:
        window.ui.comView.setCurrentIndex(com_exist)
        window.ui.btnSwitch.setText("打开")
        window.ui.iconCOM.setStyleSheet(
            "#iconCOM{image: url(:/image/image/disconnect.png);}")
        window.ui.btnSwitch.setStyleSheet(
            "#btnSwitch{background-color: red}")
        window.btnSwitchHandle()

    sys.exit(app.exec())